<template>
  <view class="my-page">
    <!-- 用户信息卡片 -->
    <view class="user-card">
      <view class="user-header">
        <view class="user-avatar">
          <!-- <view class="avatar-box" ></view> -->
          <image :src="config.beaeUrl+userInfo.avatar" mode="aspectFill" v-if="userInfo.avatar&&myToken"
            @click="getAvater" />
          <image src="/static/index/greyIcon.png" mode="aspectFill" v-if="!userInfo.avatar&&!myToken" />
          <image src=" /static/index/blueIcon.png" @click="getAvater" mode="aspectFill"
            v-if="myToken&&!userInfo.avatar" />
          <view class="role-tag">
            <view class="role-tag-item" @click="handleLogin">{{myToken?userInfo.nickName||'':'请登录'}}</view>
          </view>
        </view>
        <view class="user-info">
          <view class="name-row">
            <text class="name">手机号</text>
            <text class="time" style="font-size: 32rpx;"> {{userInfo.phonenumber||'-'}} </text>
          </view>
          <view class="name-row">
            <text class="name">用户名</text>
            <text class="time" style="font-size: 32rpx;">
              <input type="text" placeholder="请输入" v-model="userInfo.nickName" @blur="getNickName" />
            </text>
          </view>
          <view class="name-row" @click="handleStore">
            <text class="name">所属店铺</text>
            <view class="time">
              <view style="font-size: 32rpx;">{{storeName||'暂无'}}</view>
              <view class="time-arrow" v-if="columns.length>0">
                <image src="/static/index/arrow.png" mode="aspectFit" />
              </view>
            </view>
          </view>
          <!-- 退出登录按钮 -->
          <view class="logout-btn" @click="handleLogout" v-if="userInfo.userName">
            <image class="logout-icon" src="/static/index/my_icon.png" mode="aspectFit" />
            <text>退出登录</text>
          </view>
        </view>
      </view>
    </view>
    <uv-picker ref="picker" :columns="columns" @confirm="confirm"></uv-picker>
    <!-- 底部导航栏 -->
    <tab-bar></tab-bar>
  </view>
</template>

<script setup>
  import {
    ref
  } from 'vue'
  import {
    useUserStore
  } from '@/stores/user.js'
  import {
    getStoreList,
    getInfo,
    uploadAvatar
  } from '@/api/index.js'
  import config from '@/config/public'
  import {
    changeInfo
  } from '@/utils/lodash.js'
  import {
    onShow
  } from '@dcloudio/uni-app'
  import TabBar from '@/components/TabBar/index.vue'

  const userInfo = ref({})
  const myToken = ref(null)
  const storeList = ref([
    []
  ])
  const columns = ref([
    []
  ])
  const picker = ref(null)
  const storeName = ref('')
  const userStore = useUserStore()

  onShow(() => {
    myToken.value = uni.getStorageInfoSync('token')
    getInfoData()
  })

  const getInfoData = () => {
    getInfo().then(res => {
      if (res.code == 200) {
        userStore.setUserInfo(res.data)
        userInfo.value = res.data
        console.log(userInfo.value.avatar, '-----------avatar', config.beaeUrl)
        getList()
      }
    })
  }

  const getNickName = async () => {
    if (!userInfo.value.nickName) {
      uni.showToast({
        title: '昵称不能为空',
        icon: 'none'
      })
      return
    }
    const res = await changeInfo({
      nickName: userInfo.value.nickName
    }, '/applet/user/updateNickName')
    if (res.code == 200) {
      getInfoData()
    }
  }

  const getList = () => {
    storeList.value = []
    columns.value[0] = []
    getStoreList().then(res => {
      if (res.code == 200) {
        storeList.value = res.data
        if (userInfo.value.storeId) {
          storeName.value = storeList.value.filter(item => item.id == userInfo.value.storeId)[0].name
        } else {
          storeName.value = storeList.value[0].name
          userInfo.value.storeId = storeList.value[0].id
        }

        res.data.map(item => {
          columns.value[0].push(item.name)
        })
      }
    })
  }

  const changeStore = async (id) => {
    const res = await changeInfo({
      storeId: id
    }, '/applet/user/bindingStore')
    if (res.code == 200) {
      getInfoData()
      uni.removeStorageSync('selectedInfo')
    }
  }

  const handleLogin = () => {
    if (!userInfo.value.userName) {
      uni.navigateTo({
        url: '/pages/my/login'
      })
    }
  }

  const getAvater = () => {
    uni.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFilePaths[0]
        uni.showLoading({
          title: '上传中...',
          mask: true
        })

        uni.uploadFile({
          url: `${config.beaeUrl}/applet/user/avatar `, // 替换为实际的上传接口地址
          filePath: tempFilePath,
          name: 'avatarfile',
          header: {
            'Authorization': uni.getStorageSync('token')
          },
          success: (uploadRes) => {
            const data = JSON.parse(uploadRes.data)

            if (data.code === 200) {
              // 更新头像
              userInfo.value.avatar = data.imgUrl
              console.log(data, 'data--------------', userInfo.value)
              // 更新本地存储
              getInfoData()
              uni.showToast({
                title: '上传成功',
                icon: 'success'
              })
            } else {
              uni.showToast({
                title: data.msg || '上传失败',
                icon: 'none'
              })
            }
          },
          fail: (err) => {
            console.error('上传失败：', err)
            uni.showToast({
              title: '上传失败，请重试',
              icon: 'none'
            })
          },
          complete: () => {
            uni.hideLoading()
          }
        })
      }
    })
  }

  // 退出登录
  const handleLogout = () => {
    uni.showModal({
      title: '提示',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          uni.removeStorageSync('token')
          uni.removeStorageSync('userInfo')
          uni.removeStorageSync('selectedInfo')
          uni.removeStorageSync('machineInfo')
          uni.removeStorageSync('historySearchList1')
          uni.removeStorageSync('historySearchList2')
          uni.reLaunch({
            url: '/pages/my/login'
          })

        }
      }
    })
  }

  // 切换门店
  const handleStore = () => {
    if (!storeList.value[0]) {
      uni.showToast({
        title: '暂无门店',
        icon: 'none'
      })
      return
    }
    picker.value.open()
  }

  // 确认选择
  const confirm = (e) => {
    userInfo.value.storeName = storeList.value[e.indexs[0]].name
    changeStore(storeList.value[e.indexs[0]].id)
  }
</script>

<style lang="scss" scoped>
  .my-page {
    min-height: 100vh;
    background: #F5F5F5;
    padding: 20rpx;
    box-sizing: border-box;
    background-image: url('@/static/index/bg_all.png');
    background-size: 100% 100%;

    .user-card {
      margin-bottom: 20rpx;

      .user-header {
        margin: 130rpx 20rpx 80rpx;

        .user-avatar {
          display: flex;
          align-items: center;
          justify-content: flex-start;
          margin-left: 30rpx;

          image {
            width: 130rpx;
            height: 130rpx;
            border-radius: 50%;
            margin-right: 30rpx;
          }
        }

        .role-tag {
          color: #000;
          font-size: 36rpx;
        }

        .avatar-box {
          position: relative;
          width: fit-content;
          width: 130rpx;
          height: 130rpx;
          line-height: 130rpx;
          text-align: center;
          font-size: 40rpx;
          border-radius: 50%;
          color: #fff;
          background: #DFDFDF;
          margin-right: 30rpx;
          margin-left: 20rpx;
        }

        .user-info {
          height: calc(100vh - 630rpx);
          background: #FFFFFF;
          border-radius: 20rpx;
          padding: 40rpx;
          margin-top: 50rpx;
          position: relative;
          overflow: hidden;

          .name-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30rpx;
            border-bottom: 1rpx solid #f3f1f1;
            padding-bottom: 30rpx;

            &:nth-child(3) {
              border-bottom: none;
              padding-bottom: 0;
              margin-bottom: 0;
            }

            .name {
              font-size: 30rpx;
              color: #121836;
            }

            .time {
              font-size: 28rpx;
              color: #9F9F9F;
              display: flex;
              align-items: center;
              justify-content: space-between;
              text-align: right;

              .time-arrow {
                padding-top: 4rpx;
                margin-left: 10rpx;

                image {
                  width: 18rpx;
                  height: 20rpx;
                }
              }
            }
          }
        }
      }
    }

    .logout-btn {
      position: absolute;
      bottom: 0;
      left: 40rpx;
      right: 40rpx;
      background: #FFFFFF;
      height: 120rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      border-top: 1rpx solid #e4e1e1;

      .logout-icon {
        width: 40rpx;
        height: 40rpx;
        margin-right: 8rpx;
      }

      text {
        font-size: 28rpx;
        color: #666666;
      }
    }
  }
</style>